package cn.com.xiaoshoujia.utils;

import cn.com.xiaoshoujia.activities.controller.ActivitiesController;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by yangrui on 2017/7/18.
 */
public class BaseController {

    public static final Logger logger = LoggerFactory.getLogger(ActivitiesController.class);

    public static final String mkey = "topSales@888";

    public static Long getUseId(String pkProduct) {
        if (StringUtils.trimToNull(pkProduct) == null)
            return null;
        Long id = null;
        if (pkProduct.matches("^[0-9]*$")) {
            try {
                id = Long.valueOf(pkProduct);
                if (id != null && id > 960)  //兼容扫之前产品的同时防止后续产品被描
                    id = null;
            } catch (Exception e) {
                logger.error("产品ID转码异常 {}", pkProduct);
            }
        } else {
            Map<String, Object> map = getId(pkProduct);
            if (map != null)
                id = (Long) map.get("id");
        }
        return id;
    }

    public static Map<String, Object> getId(String comCode) {
        Map<String, Object> map = new HashedMap();
        Long cid = null;
        if (StringUtils.trimToNull(comCode) == null)
            return null;
        AtomicInteger mt = new AtomicInteger(2);
        String encodekey = null;
        String decodekey = null;
        try {
            logger.debug("参数校验 原始 {}", comCode);
            encodekey = URLEncoder.encode(comCode, "UTF-8");
            decodekey = URLDecoder.decode(comCode, "UTF-8");
            logger.debug("参数校验 encodekey: {} , decodekey: {}", encodekey, decodekey);
        } catch (Exception e) {
            logger.error("转码异常 {}", comCode);

        }
        String[] codes = {comCode, encodekey, decodekey};
        String cidstr = null;
        do {

            logger.debug("解密 {}", codes[mt.get()]);
            cidstr = Endecrypt.get3DESDecrypt(codes[mt.get()], mkey);

            if (StringUtils.trimToNull(cidstr) != null) {
                try {
                    cid = Long.valueOf(cidstr);
                    logger.debug("解密成功 cidstr:{}", cidstr);
                    map.put("id", cid);
                    map.put("code", encodekey);
                    break;
                } catch (Exception e) {
                    logger.debug("解密失败 cidstr:{}", cidstr);
                    cidstr = null;
                }
            }
        } while (StringUtils.trimToNull(cidstr) == null && mt.getAndDecrement() > 0);

        if (map.size() < 1) {
            logger.debug("最终解密失败");
            return null;
        }

        return map;
    }
}
